﻿using AuthorityManagement.Model;
using AuthorityManagement.Model.Dto.RoleDto;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NPOI;
using NPOI.HPSF;
using NPOI.OpenXmlFormats.Wordprocessing;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using static AuthorityManagement.Helper.RuturnHelper;

namespace AuthorityManagement.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RoleController : ControllerBase
    {
        private readonly ISqlSugarClient _Db;
        public RoleController(ISqlSugarClient db)
        {
            _Db = db;
        }
        /// <summary>
        /// 获取详情数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetRoleInfo(string id)
        {
            var data = await _Db.Queryable<Role>().Where(it => it.Id == id).Select(it => new RoleInfoOutput { Id = it.Id, RoleCode = it.RoleCode, RoleName = it.RoleName, CreateTime = it.CreateTime, Status = it.Status }).FirstAsync();
            return new { list = data };
        }
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("")]
        [Authorize]
        public async Task<dynamic> GetRoleList([FromBody] RoleQueryInput input)
        {
            var data = await _Db.Queryable<Role>()
                .Where(it => it.DeleteMark == null)
                .WhereIF(!string.IsNullOrEmpty(input.RoleCode), it => it.RoleCode.Contains(input.RoleCode))
                .WhereIF(!string.IsNullOrEmpty(input.RoleName), it => it.RoleName.Contains(input.RoleName))
                .Select(it => new RoleInfoOutput
                {
                    Id = it.Id,
                    RoleCode = it.RoleCode,
                    RoleName = it.RoleName,
                    CreateTime = it.CreateTime,
                    Status = it.Status
                }).ToPageListAsync(input.currentpage, input.pagesize);
            return new { list = data, count = data.Count };
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("Create")]
        public async Task<dynamic> Create([FromBody] RoleCrInput input)
        {
            var data = input.Adapt<Role>();
            data.Id = Guid.NewGuid().ToString();
            data.CreateTime = DateTime.Now;
            data.CreateUser = "admin";
            var isOk = await _Db.Insertable(data).ExecuteCommandAsync();
            if (isOk < 1)
            {
                return RR.Error("新增失败！");
            }
            else
            {
                return RR.Success("新增成功！");
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("Update")]
        public async Task<dynamic> Update(string id, [FromBody] RoleUpInput input)
        {
            var data = input.Adapt<Role>();
            var isOk = await _Db.Updateable(data).Where(it => it.Id == id).ExecuteCommandAsync();
            if (isOk < 1)
            {
                return RR.Error("编辑失败！");
            }
            else
            {
                return RR.Success("编辑成功！");
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("Delete")]
        public async Task<dynamic> Delete(string id)
        {
            var isOk = await _Db.Deleteable<Role>().Where(it => it.Id == id).ExecuteCommandAsync();
            if (isOk < 1)
            {
                return RR.Error("删除失败！");
            }
            else
            {
                return RR.Success("删除成功！");
            }
        }

        /// <summary>
        /// 批量删除角色数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete("BatchDelete")]
        public async Task BatchDelete(List<string> ids)
        {
            foreach (var item in ids)
            {
                await Delete(item);
            }
        }

        /// <summary>
        /// 获取左侧用户数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetLeftList")]
        public async Task<dynamic> GetLeftList(string RoleId)
        {
            //根据角色id获取用户id 查用户表不包含用户id的列表

            //var userid = await _Db.Queryable<User_Role>().Where(it => it.RoleId == RoleId).Select(it => it.UserId).ToListAsync();
            //var data = await _Db.Queryable<User>().Where(it => !userid.Contains(it.Id)).Select(it => new { key = it.Id, label = it.UserName }).ToListAsync();
            var data = await _Db.Queryable<User>().Where(it => it.DeleteMark == null).Select(it => new { key = it.Id, label = it.UserName }).ToListAsync();
            return new { list = data };
        }

        /// <summary>
        /// 获取右侧角色已拥有用户
        /// </summary>
        /// <param name="RoleId"></param>
        /// <returns></returns>
        [HttpGet("GetRightList")]
        public async Task<dynamic> GetRightList(string RoleId)
        {
            var data = await _Db.Queryable<User_Role>().Where(it => it.RoleId == RoleId).Select(it => new { key = it.UserId, label = SqlFunc.Subqueryable<User>().Where(u => u.Id == it.UserId).Select(u => u.UserName) }).ToListAsync();
            return new { list = data };
        }

        /// <summary>
        /// 提交用户角色信息
        /// </summary>
        /// <param name="RoleId">角色id</param>
        /// <param name="UserIds">用户list</param>
        /// <returns></returns>
        [HttpPost("SubmitRoleUser")]
        public async Task<dynamic> SubmitRoleUser(string RoleId, List<string> UserIds)
        {
            /*首先把该角色拥有的数据删除 然后遍历添加用户角色数据
             */
            //删除用户角色数据
            await _Db.Deleteable<User_Role>().Where(it => it.RoleId == RoleId).ExecuteCommandAsync();
            List<User_Role> userRoleList = new List<User_Role>();
            //遍历新增
            foreach (var item in UserIds)
            {
                User_Role role = new User_Role();
                role.Id = Guid.NewGuid().ToString();
                role.RoleId = RoleId;
                role.UserId = item;
                role.CreateTime = DateTime.Now;
                role.CreateUser = "admin";
                userRoleList.Add(role);
            }
            var isOk = await _Db.Insertable(userRoleList).ExecuteCommandAsync();
            if (!(isOk > 0))
            {
                return RR.Error("操作失败");
            }
            else
            {
                return RR.Success("操作成功");
            }
        }

        /// <summary>
        /// 提交角色所属菜单
        /// </summary>
        /// <param name="RoleId"></param>
        /// <param name="MenuIds"></param>
        /// <returns></returns>
        [HttpPost("SubmitPerssion")]
        public async Task<dynamic> SubmitPerssion(string RoleId, List<string> MenuIds)
        {
            /*删除用户拥有菜单 添加用户菜单
             * 可能角色没有拥有的菜单 所以!(data>0)会提示报错
             */
            try
            {
                _Db.Ado.BeginTran();
                var data = await _Db.Deleteable<Role_Menu>().Where(it => it.RoleId == RoleId).ExecuteCommandAsync();
                List<Role_Menu> rolemenus = new List<Role_Menu>();
                foreach (var item in MenuIds)
                {
                    Role_Menu menu = new Role_Menu();
                    menu.Id = Guid.NewGuid().ToString();
                    menu.RoleId = RoleId;
                    menu.MenuId = item;
                    menu.CreateTime = DateTime.Now;
                    menu.CreateUser = "admin";
                    rolemenus.Add(menu);
                }
                var isOk = await _Db.Insertable(rolemenus).ExecuteCommandAsync();
                if (!(isOk > 0) /*|| !(data > 0)*/)
                {
                    _Db.Ado.RollbackTran();
                    return RR.Error("操作失败！");
                }
                else
                {
                    _Db.Ado.CommitTran();
                    return RR.Success("操作成功");
                }
            }
            catch (Exception ex)
            {
                _Db.Ado.RollbackTran();
                throw;
            }

        }
    }
}
